package com.cnwow.status;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class WowStatusActivity extends Activity {

	private ListView listView = null;
	private EditText search_input = null;
	private Filter filter = null;
	private TextView titlebar_right = null;
	private List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();;
	private WowServerStatus wss = new WowServerStatus();
	private SimpleAdapter adapter = null;
	private ImageButton search_button = null;
	private InputMethodManager imm = null;

	private int FOCUS_STATUS = 0;
	ProgressDialog progressDialog;
	Handler handler = new Handler() {
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			result = (List<HashMap<String, String>>) msg.getData()
					.getSerializable("result");
			adapter = new MySimpleAdapter(WowStatusActivity.this, result,
					R.layout.list_row_1, new String[] { "l", "n", "t", "s_img",
							"l_img" }, new int[] { R.id.TextView_l,
							R.id.TextView_n, R.id.TextView_t,
							R.id.image_sever_status, R.id.image_server_load });
			listView.setAdapter(adapter);
			filter = adapter.getFilter();
			titlebar_right.setText(Utils.getCurrentTime());
			progressDialog.hide();
		}
	};

	@SuppressWarnings("unchecked")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 自定义标题栏 step1
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.all_server_list);
		// 自定义标题栏 step2
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.new_titlebar);

		titlebar_right = (TextView) findViewById(R.id.titlebar_right);

		listView = (ListView) findViewById(R.id.layout1_list);

		// result = (List<HashMap<String, String>>) wss.getWowServerStatus();

		adapter = new MySimpleAdapter(this, result, R.layout.list_row_1,
				new String[] { "l", "n", "t", "s_img", "l_img" }, new int[] {
						R.id.TextView_l, R.id.TextView_n, R.id.TextView_t,
						R.id.image_sever_status, R.id.image_server_load });

		listView.setAdapter(adapter);
		filter = adapter.getFilter();

		search_input = (EditText) findViewById(R.id.search_input);
		search_input.setInputType(InputType.TYPE_NULL);

		search_input.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				search_input.setInputType(InputType.TYPE_CLASS_TEXT);
				search_input.onTouchEvent(event);
				return true;
			}

		});

		search_button = (ImageButton) findViewById(R.id.search_button);

		setSearchBoxLength();
		// search
		search_input.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				// 清空搜索输入框时，刷新列表。
				if (s.toString().equals("")) {
					filter.filter(s);

					search_button.setClickable(false);
					
					hideSoftKeyBoard();
					
				} else {
					search_button.setClickable(true);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

		});

		search_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// 输入框不为空的时候，执行搜索
				if (!search_input.getText().equals("")
						&& search_input.getText() != null) {
					// 隐藏软键盘
					hideSoftKeyBoard();

					filter.filter((CharSequence) search_input.getText());

					Toast.makeText(WowStatusActivity.this, R.string.searching,
							Toast.LENGTH_SHORT).show();


				}
			}

		});

		search_button.setClickable(false);

		// ProgressDialog
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Loading...");

		fetchList();

	}

	public void fetchList() {

		progressDialog.show();

		new Thread(new Runnable() {
			public void run() {
				result = (List<HashMap<String, String>>) wss
						.getWowServerStatus();
				Bundle b = new Bundle();
				b.putSerializable("result", (Serializable) result);
				Message msg = new Message();
				msg.setData(b);
				handler.sendMessage(msg);
			}
		}).start();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST + 1, 1, "刷新").setIcon(
				android.R.drawable.ic_input_get);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case Menu.FIRST + 1:
			fetchList();
			break;
		}
		return false;
	}

	private void setSearchBoxLength() {
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();

		search_input.setWidth(display.getWidth() - 55);
	}
	
	// 隐藏软键盘
	private void hideSoftKeyBoard() {
		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
		.hideSoftInputFromWindow(WowStatusActivity.this
				.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            
			finish();
			
            return false;
        }		
		
		return super.onKeyDown(keyCode, event);
	}

}